package org.filecollector.msgcontroller.listener;

import lombok.NonNull;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

class ListenerCLI implements BasicsListener {
    @NonNull final InputStream is;
    int size = 2;

    ListenerCLI(InputStream is) {
        this.is = is;
    }

    ListenerCLI(InputStream is, int size) {
        this.is = is;
        this.size = size;
    }

    @Override
    public synchronized String readNext() {
        var characters = new StringBuilder();
        var syms = new byte[size];
        ByteBuffer buf;
        Character ch;
        int retCheck;
        try {
            while (true) {
                retCheck = is.read(syms);
                if (retCheck == -1) {
                    throw new InputStreamClosedException();
                }
                if (retCheck != size) {
                    throw new RuntimeException("Incorrect size");
                }
                buf = ByteBuffer.wrap(syms);
                ch = buf.getChar();
                if (ch.equals(Character.MIN_VALUE)) {
                    break;
                }
                characters.append(ch);
            }
        } catch (IOException exception) {
            throw new RuntimeException("IOException occurred");
        } catch (InputStreamClosedException e) {
            throw e;
        }
        return characters.toString();
    }
}
